package com.bxd.baodan.widget;


import android.content.Context;
import android.content.res.TypedArray;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bxd.baodan.R;
import com.bxd.baodan.util.StringUtil;

/**
 * Created by yetwish on 2015-05-11
 */

public class SearchView extends LinearLayout implements View.OnClickListener {


    /**
     * 输入框
     */
    public EditText et;

    /**
     * 删除键
     */
    private ImageView ivDelete;

    /**
     * 返回按钮
     */
    private TextView btnBack;

    /**
     * 上下文对象
     */
    private Context mContext;

    public View back;

    /**
     * 弹出列表
     */
//	private ListView lvTips;

    /**
     * 提示adapter （推荐adapter）
     */
//	private ArrayAdapter<String> mHintAdapter;

    /**
     * 自动补全adapter 只显示名字
     */
    private ArrayAdapter<String> mAutoCompleteAdapter;
    /**
     * 自动补全adapter 显示对象
     */
    private BaseAdapter mAutoCompleteBaseAdapter;

    /**
     * 搜索回调接口
     */
    private SearchView.SearchViewListener mListener;

    private int layout;

    /**
     * 设置搜索回调接口
     *
     * @param listener 监听者
     */
    public void setSearchViewListener(SearchView.SearchViewListener listener) {
        mListener = listener;
    }

    public SearchView(Context context, AttributeSet attrs) {
        super(context, attrs);

        setOrientation(LinearLayout.HORIZONTAL);
        TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.SearchView);
        layout = mTypedArray.getInteger(R.styleable.SearchView_layout, R.layout.search_layout);
        mTypedArray.recycle();
        mContext = context;
        initViews(context);
    }

    private void initViews(Context context) {
        // 添加搜索的布局
        LayoutInflater.from(context).inflate(layout, this);

        et = (EditText) findViewById(R.id.searchview_edit);

        ivDelete = (ImageView) findViewById(R.id.searchview_iv_del);
        btnBack = (TextView) findViewById(R.id.search_btn_back);
        back =  findViewById(R.id.back);

      //  et.setSelection(et.getText().length());

        ivDelete.setOnClickListener(this);
        btnBack.setOnClickListener(this);

        et.addTextChangedListener(new SearchView.EditChangedListener());
        et.setOnClickListener(this);
        et.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId,
                                          KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    notifyStartSearching(et.getText().toString(), -1);
                }
                return true;
            }
        });
    }

    public void setetInputText(String text) {
        et.setText(text);
    }

    /**
     * 通知监听者 进行搜索操作
     *
     * @param text
     */
    public void notifyStartSearching(String text, int cate_id) {
        if (mListener != null) {
            mListener.onSearch(text, cate_id);
            et.setText(text);
        }

        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);

        imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
    }

    /**
     * 设置热搜版提示 adapter
     */
    public void setTipsHintAdapter(ArrayAdapter<String> adapter) {
    }

    /**
     * 设置自动补全adapter
     */
    public void setAutoCompleteAdapter(ArrayAdapter<String> adapter) {
        this.mAutoCompleteAdapter = adapter;
    }

    /**
     * 设置自动补全adapter List<T>
     */
    public void setAutoCompleteAdapter(BaseAdapter adapter) {
        this.mAutoCompleteBaseAdapter = adapter;
    }


    private class EditChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i2,
                                      int i3) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i2,
                                  int i3) {

            et.setSelection(charSequence.toString().length());
            if (!"".equals(charSequence.toString())) {
                ivDelete.setVisibility(VISIBLE);
                // 更新autoComplete数据
                if (mListener != null) {
                    mListener.textChanged(charSequence + "");

                }
            } else {
                ivDelete.setVisibility(GONE);
                if (mListener!= null) {
                    mListener.onEmpty();
                }

            }


        }

        @Override
        public void afterTextChanged(Editable editable) {


        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.searchview_edit:
                break;
            case R.id.searchview_iv_del:
                et.setText("");
                ivDelete.setVisibility(GONE);
                break;
            case R.id.search_btn_back:
                if (!StringUtil.isEmpty(et.getText().toString())) {

                    notifyStartSearching(et.getText().toString(), -1);

                } else {
                    Toast.makeText(mContext, "请输入关键字", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * search view回调方法
     */
    public interface SearchViewListener {

        /**
         * 联想词
         *
         * @param text 传入补全后的文本
         */
        void textChanged(String text);

        /**
         * 开始搜索
         *
         * @param text 传入输入框的文本
         */
        void onSearch(String text, int cate_id);


        /**
         * 显示历史布局
         */
        void onEmpty();
    }

    public void search(String key) {
        if (key != null && !key.isEmpty()&& mListener!= null) {
            mListener.onSearch(key,-1);
        }
    }


}
